package com.zy.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.entity.JsonResult;
import com.zy.entity.User;
import com.zy.service.impl.UserServiceImpl;
import com.zy.tools.RedisTool;
import com.zy.tools.appletsTools.MailCode;
import com.zy.tools.appletsTools.MailToolImpl;
import com.zy.tools.appletsTools.PinYinTool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.ParseException;


@Controller
@RequestMapping("/app")
public class RegisterController {
    @Autowired
    UserServiceImpl userService;
    @Autowired
    MailToolImpl mailTool;
    @Autowired
    RedisTool redisTool;
    @Autowired
    PinYinTool pinYinTool;

    /**
     * 小程序注册
     *
     * @param username
     * @param post
     * @param email
     * @param phone
     * @param birthday
     * @param emailCode
     * @param wxCode
     * @param info
     * @return com.zy.entity.JsonResult
     * @author 小宁
     * @date 2021-04-07 15:58
     */
    @ResponseBody
    @PostMapping("/register")
    public JsonResult register(String username, String post, String email, String phone, String birthday, String emailCode, String wxCode, String info) throws IOException, ParseException {
        String getCode = (String) redisTool.get(email);//判断验证码是否正确
        System.out.println(getCode);
        System.out.println(emailCode);
        if (!emailCode.equals(getCode)) {
            return new JsonResult("201", "验证码错误", "");
        }

        JSONObject json = JSON.parseObject(info);
        String path = json.get("avatarUrl").toString();
        String nickName = json.get("nickName").toString();
        json.clear();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx4c06dc20718f16d7&secret=" +
                "908185613dc6a98df3d50385c525f4a6&js_code=" + wxCode + "&grant_type=authorization_code";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = okHttpClient.newCall(request).execute();

        if (response.isSuccessful()) {
            String body = response.body().string();
            json = JSONObject.parseObject(body);
            String openid = json.getString("openid");
            System.out.println("openid " + openid);
            json.clear();

            User user = null;
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("open_id", openid);
            user = userService.getOne(userQueryWrapper);
            if (user != null) {
                return new JsonResult("201", "用户已存在", "");
            }
            QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
            userQueryWrapper1.eq("email", email);
            user = userService.getOne(userQueryWrapper1);

            if (user != null) {
                return new JsonResult("201", "邮箱已存在", "");
            }
            QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
            userQueryWrapper2.eq("phone", phone);
            user = userService.getOne(userQueryWrapper2);
            if (user != null) {
                return new JsonResult("201", "手机号已存在", "");
            }

            User addUser = new User();
            addUser.setName(username);
            addUser.setPost(post);
            addUser.setEmail(email);
            addUser.setPhone(phone);
            addUser.setBirthday(birthday);
            addUser.setOpenId(openid);
            addUser.setNickName(nickName);
            addUser.setPath(path);
            addUser.setLetter(pinYinTool.getPinYinHeadChar(username));
            userService.save(addUser);
            redisTool.del(email);
            return new JsonResult("200", "注册成功", "");
        } else {
            return new JsonResult("500", "网络错误，重试", "");
        }
    }

    /* 检测姓名、手机号、邮箱是否存在
     * @author 小宁
     * @date 2021-04-03 15:58
     * @param username
     * @param type
     * @return com.zy.entity.JsonResult
     */
    @GetMapping("/testing")
    @ResponseBody
    public JsonResult testing(String username, int type) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (type == 1) {
            userQueryWrapper.eq("name", username);
            User user = userService.getOne(userQueryWrapper);
            if (user == null) {
                return new JsonResult("200", "", "");
            } else {
                return new JsonResult("201", "姓名已存在", "");
            }
        } else if (type == 2) {
            userQueryWrapper.eq("phone", username);
            User user = userService.getOne(userQueryWrapper);
            if (user == null) {
                return new JsonResult("200", "", "");
            } else {
                return new JsonResult("201", "手机号已存在", "");
            }
        } else {
            userQueryWrapper.eq("email", username);
            User user = userService.getOne(userQueryWrapper);
            if (user == null) {
                return new JsonResult("200", "", "");
            } else {
                return new JsonResult("201", "邮箱已存在", "");
            }
        }
    }

    /* 邮箱发送验证码
     * @author 小宁
     * @date 2021-04-03 15:59
     * @param username
     * @return com.zy.entity.JsonResult
     */
    @GetMapping("/send")
    @ResponseBody
    public JsonResult send(String username) {
        Boolean keyState = redisTool.hasKey(username);
        if (keyState) {
            return new JsonResult("201", "禁止频繁发送", "");
        }
        MailCode mailCode = new MailCode();
        String code = mailCode.code();
        Boolean state = redisTool.set(username, code, 60 * 5);
        if (state) {
            mailTool.sendSimpleMail(username, "【致一科技】", "您的验证码为：" + code + "，该验证码5分钟内有效。");
            return new JsonResult("200", "邮件发送成功", "");
        } else {
            return new JsonResult("201", "邮件发送失败", "");
        }
    }
}
